package top.lshaci.learning.alibaba.cloud.sentinel.hello.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.lshaci.learning.alibaba.cloud.sentinel.hello.feign.EchoService;

/**
 * HelloService
 *
 * @author lshaci
 * @since 1.0.0
 */
@Slf4j
@Service
public class HelloService {

    @Autowired
    EchoService echoService;

    /**
     * @SentinelResource https://github.com/alibaba/Sentinel/wiki/%E6%B3%A8%E8%A7%A3%E6%94%AF%E6%8C%81
     *  blockHandler: 会在资源方法被限流、降级、系统保护的时候调用；需要定义在当前类
     *  fallback: 会针对所有类型的异常；1、定义在当前类，2、定义在其它类中的static方法，指定fallbackClass
     */
    @SentinelResource(value = "sayHello", blockHandler = "sayHelloBlockHandler")
    public String sayHello(String name) {
        log.debug("sayHello: {}", name);
        String echo = echoService.echo(name);
        return "Hello, " + echo;
    }

    public String sayHelloBlockHandler(String name, BlockException e) {
        log.error("流控", e);
        return "Fallback, " + name;
    }
}
